package param

/*
 * @Author: Wangjun
 * @Date: 2021-05-15 22:43:19
 * @LastEditTime: 2025-10-06 09:01:40
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \golib\autoroute\controller\param.go
 * hnxr
 */

import (
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

// Param 自动读取参数
type Param struct {
	m map[string]string
}

func NewParam(kv map[string]string) *Param {
	m := new(Param)
	if kv != nil {
		m.m = kv
	} else {
		m.m = map[string]string{}
	}
	return m
}

func NewParamByURL(rawQuery string) *Param {
	m := new(Param)
	//r.ParseForm()
	m.m = map[string]string{}
	vals, _ := url.ParseQuery(rawQuery)
	for k, v := range vals {
		m.m[k] = v[0]
	}
	return m
}

// Set 设置键
func (m *Param) Set(key, value string) {
	m.m[key] = value
}

// GetString 获取字符串
func (m *Param) GetString(key string) string {
	return m.m[key]
}

// GetTrimString 获取去掉2边空格后的字符串
func (m *Param) GetTrimString(key string) string {
	return strings.TrimSpace(m.m[key])
}

// GetInt 获取INT数据
func (m *Param) GetInt(key string) (int, error) {
	ival := strings.TrimSpace(m.m[key])
	return strconv.Atoi(ival)
}

// GetMap 获取全部参数
func (m *Param) GetMap() map[string]string {
	return m.m
}

// GetInt64 获取INT数据
func (m *Param) GetInt64(key string) (int64, error) {
	return strconv.ParseInt(m.m[key], 10, 0)
}

// GetFloat 获取float64数据
func (m *Param) GetFloat(key string) (float64, error) {
	return strconv.ParseFloat(m.m[key], 64)
}

// GetBool 获取bool数据
func (m *Param) GetBool(key string) bool {
	value := strings.ToLower(m.m[key])
	switch value {
	case "1", "true","y","yes":
		return true
	}
	return false
}

// 解析表单参数
func (m *Param)Form(r *http.Request) *Param {
	r.ParseForm()
	for k, v := range r.PostForm {
		m.Set(k, v[0])
	}
	return m
}